<?php
/**
*  PHP Template functions
* @author yubing
*/
defined('ROOT') || exit('forbidden');
class template{
    public static function inc($tpl_file) {
        $tpl_dir   =  ROOT . 'templates/';
        $parsed_dir    = ROOT.'data/templates_c/';
        $parsed_file  = $parsed_dir .$tpl_file .'.php';
        if (@filemtime($parsed_file) < filemtime($tpl_dir. $tpl_file)) {
            if (!($str=file_get_contents($tpl_dir . $tpl_file))) {
                exit("read tpl $tpl_file error");
            }
            $str = self::_parseTag($str);            
            is_dir(dirname($parsed_file)) || mkdir(dirname($parsed_file), 0755, true);
            file_put_contents($parsed_file,$str);
        }
        return $parsed_file;
        
    }
    /**
     * @desc parse_tag template file
     */
    private static function _parseTag($str){
        $str = preg_replace('/\{\s*include file=["\']?([a-zA-Z0-9\/\\_.]+)[\'"]?\s*\}/i', "<?php include template::inc('\\1');?>", $str);
        
        $str = preg_replace(array('/<!--\s*if\s*(\[|\()(.+?)(\]|\))\s*{\s*-->/is',
        '/<!--\s*elseif(\[|\()(.+?)(\]|\))\s*{\s*-->/is',
        '/<!--\s*else\s*{\s*-->/is',
        '/<!--\s*}\s*-->/',
		'/<!--\s*foreach\s*\((.*)\s*(as)\s*(.+)\s*\)\s*{\s*-->/i',
        '/\{\$([a-zA-Z0-9_\'\"\[\]$]+)\}/',
        '/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/',
        '/\{echo (.*)\}/',
        ),
        array('<?php if(\\2){?>',
        '<?php }elseif(\\2){?>',
        '<?php }else{?>',
        '<?php }?>',
        '<?php foreach((array)\\1 AS \\3){?>',
        '<?php echo $\\1;?>',
        '<?php echo \\1;?>',
        '<?php echo \\1;?>',
        ),
        $str);
        
        return $str;
    }
}
